package com.nineclock.signIn.service.impl;

import afu.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.DateTimeUtil;
import com.nineclock.signIn.dto.SignInfoAllUserListDTO;
import com.nineclock.signIn.dto.SignInfoDTO;
import com.nineclock.signIn.mapper.SignInfoMapper;
import com.nineclock.signIn.pojo.SignInfo;
import com.nineclock.signIn.service.SignInLisService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Xu
 * @Date: 2021/12/02/12:06
 */
@Service
@Transactional
@Slf4j
public class SignInLisServiceImpl implements SignInLisService {
    @Autowired
    private SysCompanyUserFeign companyUserFeign;

    @Autowired
    private SignInfoMapper signInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 获取团队员工打卡列表
     * @param dateStr
     * @return
     */
    @Override
    public List<SignInfoAllUserListDTO> findAllSingInList(String dateStr) {
        //获本公司指定日期的打卡列表  dateStr 是字符串 2020-12-12格式
        List<SignInfoAllUserListDTO> signInfoAllUserList = new ArrayList<>();
        //得到该公司所有员工信息
        List<SysCompanyUserDTO> companyUserDTOS = companyUserFeign.queryAllCompanyUser().getData();

        //参数校验
        if (CollectionUtils.isEmpty(companyUserDTOS)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //查询该公司当日打卡的信息
        LambdaQueryWrapper<SignInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SignInfo::getCompanyId, CurrentUserHolder.get().getCompanyId()); //当前公司
        wrapper.eq(SignInfo::getCreateDate,dateStr);//当前日期
        List<SignInfo> signDateList = signInfoMapper.selectList(wrapper);

        //参数校验
        if (CollectionUtils.isEmpty(signDateList)){
            throw new NcException(ResponseEnum.SIGN_DATA_NULL);
        }
        //封装SignInfoDTO对象
        List<SignInfoDTO> signInfoDTOList = BeanHelper.copyWithCollection(signDateList, SignInfoDTO.class);

        //将姓名username字段添加到 SignInfoDTO对象中  得到
        List<SignInfoDTO> signInfoForUserList = signInfoDTOList.stream().map(signInfoDTO -> {
            SignInfoAllUserListDTO signInfoAllUser= new  SignInfoAllUserListDTO();
            for (SysCompanyUserDTO companyUserDTO : companyUserDTOS) {
                //如果签到员工id与公司员工的对象Id相同 将companyUserDTO.getUserName 赋值给SignInfoDTO
                if (signInfoDTO.getCompanyUserId()==companyUserDTO.getId()){
                    //查询当前用户当日的签到次数
                    //切割2020-12-12 得到月份 得到月份  日期的 几个
                    Map<String, String> stringStringMap = breakUpStr(dateStr);
//                    String month = stringStringMap.get("month");
//                    String day = stringStringMap.get("day");
                    //获取打卡的month & day
                    String key = "SignInMonth" + CurrentUserHolder.get().getCompanyId() + signInfoDTO.getCompanyUserId() + stringStringMap.get("month") + stringStringMap.get("day");
                    //根据key查询value
                    Object object = redisTemplate.opsForValue().get(key); //得到当天你打卡的总次数
                    String dayCount = object.toString(); //字符穿类型
                    signInfoDTO.setDayCount(dayCount);
                    //获取当前用户本月的本月签到次数 调用getMonthSignIn();
//                    Integer monthSignIn = getMonthSignIn(signInfoDTO.getCompanyUserId(), dateStr);
//                    String monthCount = String.valueOf(monthSignIn);
                    String monthCount = String.valueOf(getMonthSignIn(signInfoDTO.getCompanyUserId(), dateStr));
                    signInfoDTO.setMonthCount(monthCount);
                    signInfoDTO.setUserName(companyUserDTO.getUserName());
                }
            }
            return signInfoDTO;
        }).collect(Collectors.toList());
        //根据名字分组 获取打卡的纪录的DTO
        Map<String, List<SignInfoDTO>> signInfoForUserMap
                = signInfoForUserList.stream().collect(Collectors.groupingBy(SignInfoDTO::getUserName));
        //获取不重复的用户名集合
        Set<String> UsernameStr = signInfoForUserMap.keySet();
        //遍历signInfoForUserList
//        SignInfoAllUserListDTO signInfoAllUser = new SignInfoAllUserListDTO();
        //遍历用户名;;列表
        for (String userName : UsernameStr) {
            SignInfoAllUserListDTO signInfoAllUser = new SignInfoAllUserListDTO();
            //封装username
            signInfoAllUser.setUsername(userName);
            //Map集合 根据userName差早签到List对象
            List<SignInfoDTO> signInfoDTOS = signInfoForUserMap.get(userName);
            //封装签到对象
            signInfoAllUser.setSignResponseList(signInfoDTOS);
            //添加到对用数据
            signInfoAllUserList.add(signInfoAllUser);
        }

    return  signInfoAllUserList;

    }

    /**
     * 得到当前用户整个月的签到此时
     * @param companyUserId  用户id
     * @param dateStr  日期 2020-12-12
     */
    private Integer getMonthSignIn(Long companyUserId, String dateStr) {
        Map<String, String> dateMap = breakUpStr(dateStr);
        //得到月份
        String month = dateMap.get("month");
        //遍历拼接天数  1-31
        String day;
        //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
        List<String>  dayList = new ArrayList<>();
        for (int i = 1; i < 32; i++) {
           day = i +"";
            dayList.add(day);
        }
        int sum = 0;
        try {
            for (String dayStr : dayList) {

                String key = "SignInMonth" + CurrentUserHolder.get().getCompanyId() + companyUserId + month + dayStr;
//                String key1 = "SignInMonth" + CurrentUserHolder.get().getCompanyId() + 1L + "12" + "2";

                Object s = redisTemplate.opsForValue().get(key);
                if (s!=null){
                    sum = sum + Integer.parseInt(s.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  sum;
    }


    /**
     * 拆分2020-12-12字符串
     * @param dateStr
     */
    private Map<String,String> breakUpStr(String dateStr) {
        Map<String, String> dateMap = new HashMap<>();
        String[] date = dateStr.split("-");
        String month = date[1].replaceFirst("^0*", ""); //12
        String day = date[2].replaceFirst("^0*", ""); //2
            dateMap.put("month",month);
            dateMap.put("day",day);
            return dateMap;
//        String key = "SignInMonth" + CurrentUserHolder.get().getCompanyId() + CurrentUserHolder.get().getCompanyUserId() + month + day;
    }

}
